package com.xinnet.mms.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.area.service.AreaService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.config.service.FlowTurnConfigService;
import com.xinnet.mms.customerConsumeManage.service.CustomerConsumeManageService;
import com.xinnet.mms.customerstate.service.CustomerStateHistService;
import com.xinnet.mms.customtransfer.service.IntentionCustomTransferService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.deptarea.service.DeptAreaService;
import com.xinnet.mms.emp.service.PartyService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.AgentConsume;
import com.xinnet.mms.entity.Area;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerConsume;
import com.xinnet.mms.entity.CustomerConsumptionDetail;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.Party;
import com.xinnet.mms.entity.Role;
import com.xinnet.mms.enums.ConsumeBusinessTypeEnmu;
import com.xinnet.mms.enums.ConsumePhaseTypeEnmu;
import com.xinnet.mms.enums.ConsumeStateEnmu;
import com.xinnet.mms.enums.ProductTypeEnum;
import com.xinnet.mms.login.service.EmpService;
import com.xinnet.mms.order.service.OrderService;
import com.xinnet.mms.utils.CustomerManage;

/**
 * 
 * 类描述：业务管理 
 * 
 * @author 王志军[wangzhijun@xinnet.com]
 * 
 * @version 1.0
 * 
 * @since 2016-1-20
 */
@Controller
@RequestMapping(value = "/serviceManage")
public class ServiceManageController {

	@Autowired
	private CustomerConsumeManageService customerConsumeManageService;

	@Autowired
	private CustomAllotService customAllotService;

	@Autowired
	private AreaService areaService;

	@Autowired
	private DeptService deptService;

	@Autowired
	private EmpCustomRelationService empCustomRelationService;

	@Autowired
	private CustomerStateHistService customerStateHistService;

	@Autowired
	private EmpService empService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private DeptAreaService deptAreaService;

	@Autowired
	FlowTurnConfigService flowTurnConfigService;
	
	@Autowired
	PartyService partyService;
	
	@Autowired
	IntentionCustomTransferService intentionCustomTransferService;

	ObjectMapper mapper = new ObjectMapper();

	private String sep=java.io.File.separator;
	/**
	 * 
	 * 方法描述：转到消耗预估记录界面
	 * 
	 * 
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2014-1-16 下午3:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/estimatePage")
	public String estimatePage(Customer customer, PageView<Customer> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model) throws Exception {
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return "redirect:/login/loginPage";
		}
		// 客户管理查询条件：所属人的部门组织Ztree Json
		String deptJson = AppGlobalContainer.deptIdToDeptJsonMap.get(currentUser.getId());
		if(deptJson==null){
			deptJson = "["
					+ deptService.getDeptTreeByDeptId(currentUser.getId()) + "]";
			AppGlobalContainer.deptIdToDeptJsonMap.put(currentUser.getId(), deptJson);
		}
		model.addAttribute("deptJson", deptJson);

		// 客户管理查询条件：所属区域
		List<Area> parentAreaList = areaService.getAreaOfClassA();
		model.addAttribute("parentAreaList", parentAreaList);

		List<Area> childAreaList = areaService.getAreaOfClassB();
		model.addAttribute("childAreaList", childAreaList);
		
		ProductTypeEnum[] productTypeEnumArray = ProductTypeEnum.values();
		model.addAttribute("productTypeEnumArray", productTypeEnumArray);
		
		ConsumeBusinessTypeEnmu[] consumeBusinessTypeEnmu = ConsumeBusinessTypeEnmu.values();
		model.addAttribute("consumeBusinessTypeEnmu", consumeBusinessTypeEnmu);
		
		ConsumePhaseTypeEnmu[] consumePhaseTypeEnmu = ConsumePhaseTypeEnmu.values();
		model.addAttribute("consumePhaseTypeEnmu", consumePhaseTypeEnmu);
		
		ConsumeStateEnmu[] consumeStateEnmu = ConsumeStateEnmu.values();
		model.addAttribute("consumeStateEnmu", consumeStateEnmu);
		return "market/service/deal_estimate";
	}
	
	/**
	 * 
	 * 方法描述：转到销售过程管理界面
	 * 
	 * 
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2016-1-22 下午3:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/consumePhaseStatisticsPage")
	public String consumePhaseStatisticsPage(Customer customer, PageView<Customer> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model) throws Exception {
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return "redirect:/login/loginPage";
		}
		// 客户管理查询条件：所属人的部门组织Ztree Json
		String deptJson = AppGlobalContainer.deptIdToDeptJsonMap.get(currentUser.getId());
		if(deptJson==null){
			deptJson = "["
					+ deptService.getDeptTreeByDeptId(currentUser.getId()) + "]";
			AppGlobalContainer.deptIdToDeptJsonMap.put(currentUser.getId(), deptJson);
		}
		model.addAttribute("deptJson", deptJson);

		// 客户管理查询条件：所属区域
		List<Area> parentAreaList = areaService.getAreaOfClassA();
		model.addAttribute("parentAreaList", parentAreaList);

		List<Area> childAreaList = areaService.getAreaOfClassB();
		model.addAttribute("childAreaList", childAreaList);
		
		ProductTypeEnum[] productTypeEnumArray = ProductTypeEnum.values();
		model.addAttribute("productTypeEnumArray", productTypeEnumArray);
		
		ConsumeBusinessTypeEnmu[] consumeBusinessTypeEnmu = ConsumeBusinessTypeEnmu.values();
		model.addAttribute("consumeBusinessTypeEnmu", consumeBusinessTypeEnmu);
		
		ConsumePhaseTypeEnmu[] consumePhaseTypeEnmu = ConsumePhaseTypeEnmu.values();
		model.addAttribute("consumePhaseTypeEnmu", consumePhaseTypeEnmu);
		
		ConsumeStateEnmu[] consumeStateEnmu = ConsumeStateEnmu.values();
		model.addAttribute("consumeStateEnmu", consumeStateEnmu);
		return "market/service/consume_phasestatistics";
	}
	
	/**
	 * 
	 * 方法描述：转到销售过程管理界面
	 * 
	 * 
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2016-1-26 上午10:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/consumePhaseStatistics")
	public void consumePhaseStatistics(CustomerConsume customerConsume, PageView<Customer> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model) throws Exception {
		PrintWriter pw = response.getWriter();
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customerConsume.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customerConsume.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customerConsume.setDeptId(null);
		}
		 
		List<CustomerConsume> customerConsumeList = null;
		customerConsumeList = customerConsumeManageService.countCustomerConsume(customerConsume);
		//String customerConsumeListStr = mapper.writeValueAsString(customerConsumeList);
		JSONObject jo = new	JSONObject();
		for (CustomerConsume customerConsume2 : customerConsumeList) {
			if(customerConsume2.getConsumePhase()==null||"".equals(customerConsume2.getConsumePhase())){
				continue;
			}
			if(customerConsume2.getConsumePhase().equals("初期沟通")){
				jo.element("chuqigoutongCount", customerConsume2.getGoodsCount());
				jo.element("chuqigoutongAmount", customerConsume2.getAmount());
			}
			
			if(customerConsume2.getConsumePhase().equals("确认需求")){
				jo.element("querenxuqiuCount", customerConsume2.getGoodsCount());
				jo.element("querenxuqiuAmount", customerConsume2.getAmount());
			}
			
			if(customerConsume2.getConsumePhase().equals("方案制定")){
				jo.element("fanganzhidingCount", customerConsume2.getGoodsCount());
				jo.element("fanganzhidingAmount", customerConsume2.getAmount());
			}
			
			if(customerConsume2.getConsumePhase().equals("商务谈判")){
				jo.element("shangwutanpanCount", customerConsume2.getGoodsCount());
				jo.element("shangwutanpanAmount", customerConsume2.getAmount());
			}
			
			if(customerConsume2.getConsumePhase().equals("充值")){
				jo.element("chongzhiCount", customerConsume2.getGoodsCount());
				jo.element("chongzhiAmount", customerConsume2.getAmount());
			}
			
			if(customerConsume2.getConsumePhase().equals("消耗")){
				jo.element("xiaohaoCount", customerConsume2.getGoodsCount());
				jo.element("xiaohaoAmount", customerConsume2.getAmount());
			}
		}
		
		if(!jo.containsKey("chuqigoutongCount")){
			jo.element("chuqigoutongCount", 0);
			jo.element("chuqigoutongAmount", 0);
		}
		if(!jo.containsKey("querenxuqiuCount")){
			jo.element("querenxuqiuCount", 0);
			jo.element("querenxuqiuAmount", 0);
		}
		if(!jo.containsKey("fanganzhidingCount")){
			jo.element("fanganzhidingCount", 0);
			jo.element("fanganzhidingAmount", 0);
		}
		if(!jo.containsKey("shangwutanpanCount")){
			jo.element("shangwutanpanCount", 0);
			jo.element("shangwutanpanAmount", 0);
		}
		if(!jo.containsKey("chongzhiCount")){
			jo.element("chongzhiCount", 0);
			jo.element("chongzhiAmount", 0);
		}
		if(!jo.containsKey("xiaohaoCount")){
			jo.element("xiaohaoCount", 0);
			jo.element("xiaohaoAmount", 0);
		}
		
		
		pw.println(jo.toString());
		
	}

	/**
	 * 
	 * 方法描述：查询消耗预估记录
	 * 
	 * 
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2016-1-20 下午14:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@SuppressWarnings("unchecked")
	@RequestMapping("/estimate")
	public void queryCustomer(CustomerConsume customerConsume, PageView<CustomerConsume> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customerConsume.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customerConsume.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customerConsume.setDeptId(null);
		}

		/*PageView<Customer> pageView = customerManageService.queryCustomer(page,
				customer);*/
		List<CustomerConsume> customerConsumeList = null;
		PageView<CustomerConsume> pageView = customerConsumeManageService.queryCustomerConsume(page, customerConsume);
		
		// 获取分页List
		if (null != pageView) {
			customerConsumeList = pageView.getRecords();
		}
		
		map.put("customerConsume", customerConsume);
		String customerConsumeListStr = mapper.writeValueAsString(customerConsumeList);
		pw.println(customerConsumeListStr);
	}
	
	
	/**
	 * 
	 * 方法描述：添加客户交易
	 * 
	 * @param customerConsume
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2016-1-15 下午09:32:08
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/addCustomerConsume")
	public void addCustomerConsume(CustomerConsume customerConsume,
			HttpSession session, HttpServletResponse response) throws Exception {
		Emp emp = (Emp) session.getAttribute("currentUser");
		if (null == emp) {
			return;
		}
		PrintWriter pw = response.getWriter();
		try {
			customerConsume.setId(UUID.randomUUID().toString());
			customerConsume.setEmpId(emp.getEmpno());
			customerConsumeManageService.addCustomerConsume(customerConsume);
			pw.println("添加成功！");
		} catch(RuntimeException re){
			pw.println("添加失败,交易已存在！");
		} catch (Exception e) {
			pw.println("添加失败！");
		}
	}
	
	/**
	 * 
	 * 方法描述：修改客户交易
	 * 
	 * @param customerConsume
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2016-1-15 下午09:32:08
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/modifyCustomerConsume")
	public void modifyCustomerConsume(CustomerConsume customerConsume,
			HttpSession session, HttpServletResponse response) throws Exception {
		Emp emp = (Emp) session.getAttribute("currentUser");
		if (null == emp) {
			return;
		}
		PrintWriter pw = response.getWriter();
		try {
			customerConsumeManageService.updateCustomerConsume(customerConsume);
			pw.println("修改成功！");
		} catch (Exception e) {
			pw.println("修改失败！");
		}
	}
	
	/**
	 * 
	 * 方法描述：修改客户交易
	 * 
	 * @param customerConsume
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2016-1-15 下午09:32:08
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/delCustomerConsume")
	public void delCustomerConsume(CustomerConsume customerConsume,
			HttpSession session, HttpServletResponse response) throws Exception {
		Emp emp = (Emp) session.getAttribute("currentUser");
		if (null == emp) {
			return;
		}
		PrintWriter pw = response.getWriter();
		try {
			customerConsumeManageService.delCustomerConsume(customerConsume);
			pw.println("修改成功！");
		} catch (Exception e) {
			pw.println("修改失败！");
		}
	}
	
	
	/**
	 * 
	 * 
	 * 功能描述：导出业绩数据
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年4月30日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 *
	 */
	@RequestMapping("/expDealform")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String expDealform(HttpServletRequest request,HttpServletResponse response,CustomerConsume customerConsume) {
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/temp");
		File pathFile=new File(path);
		if(!pathFile.exists()) {
			pathFile.mkdirs();
		}
		String fileName=UUID.randomUUID().toString()+"_消耗预估.xls";
		File file=new File(path,fileName);
		// 获取当前登录用户
		Emp currentUser = (Emp) request.getSession().getAttribute("currentUser");
		if (null == currentUser) {
			return "errors/error";
		}
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customerConsume.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customerConsume.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) request.getSession().getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customerConsume.setDeptId(null);
		}
		
		if(file.exists()) {
			request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
			return "errors/error";
		}
					
		else {
			try {
				HSSFWorkbook ws = new HSSFWorkbook();//建立新HSSFWorkbook对象  
			    FileOutputStream fileOut = new FileOutputStream(path+sep+fileName);//创建文件流  
			    ws.write(fileOut);//把Workbook对象输出到路径path中  
			    fileOut.close();
				HSSFWorkbook book=doExpDealFormData(customerConsume,path+sep+fileName);
				if(book==null) {
					request.setAttribute("error", "该时间区间没有数据需要导出");
					return "errors/error";
				}
				book.write(new FileOutputStream(path+sep+fileName));
				
				//设置下载文件名
				String url=java.net.URLDecoder.decode(path+sep+fileName,"UTF-8");
				fileName=fileName.substring(fileName.lastIndexOf("_")+1);
				fileName=URLEncoder.encode(fileName, "UTF-8");
				response.addHeader("content-disposition","attachment;filename="+fileName);
				response.setHeader("content-type","text/html;charset=utf-8");
				response.setContentType("application/x-download");
				request.setCharacterEncoding("UTF-8");
				//下载操作
				File downLoadFile=new File(url);
				OutputStream out=response.getOutputStream();
				InputStream in=new FileInputStream(downLoadFile);
				byte[] b=new byte[1024];
				@SuppressWarnings("unused")
				int ch=0;
				while((ch=in.read(b))!=-1) {
					out.write(b,0,b.length);
				}
				in.close();
				return null;
			} catch (IOException e) {
				request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
				e.printStackTrace();
				return "errors/error";
			}
		}
	}
	
	/**
	 * @author 邢泽江 
	 * @description 会员消耗明细连接页
	 * @param customerConsume
	 * @param page
	 * @param request
	 * @param response
	 * @param session
	 * @param map
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/queryxiao")
	public String queryxiao(CustomerConsume customerConsume, PageView<CustomerConsume> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
//			return;
		}
		return "market/service/customer_deal_detail";
	}
	
	/**
	 * @author 邢泽江 
	 * @description 会员消耗明细查询方法
	 * @param customerConsume
	 * @param page
	 * @param request
	 * @param response
	 * @param session
	 * @param map
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/queryfindxiao")
	public void queryfindxiao(CustomerConsume customerConsume, PageView<CustomerConsumptionDetail> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
//			return;
		}
		PageView<CustomerConsumptionDetail> ccDetail = orderService.getCustomerConsumptionDetail(page,customerConsume);
		map.put("customerConsumptionDetail", ccDetail.getRecords());
		map.put("customerConsume", customerConsume);
		String ccDetailString = mapper.writeValueAsString(ccDetail.getRecords());
		pw.println(ccDetailString);
	}
	
	/**
	 * 
	 * @param customerConsume
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/expDealDetailform")
	public String expDealDetailform(CustomerConsume customerConsume, Model model){
		List<Party> partylist = partyService.getAllPartyByptId("subCompany");
		model.addAttribute("partylist", partylist);
		return  "market/service/customer_deal_detailform";
	}
	
	@RequestMapping("/expDealDetailformdo")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String expDealDetailformdo(HttpServletRequest request,HttpServletResponse response,CustomerConsume customerConsume) {
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/temp");
		File pathFile=new File(path);
		if(!pathFile.exists()) {
			pathFile.mkdirs();
		}
		String fileName=UUID.randomUUID().toString()+"_业绩明细.xls";
		File file=new File(path,fileName);
		// 获取当前登录用户
		Emp currentUser = (Emp) request.getSession().getAttribute("currentUser");
		if (null == currentUser) {
			return "errors/error";
		}
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customerConsume.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customerConsume.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) request.getSession().getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customerConsume.setDeptId(null);
		}
		
		if(file.exists()) {
			request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
			return "errors/error";
		}
					
		else {
			try {
				HSSFWorkbook ws = new HSSFWorkbook();//建立新HSSFWorkbook对象  
			    FileOutputStream fileOut = new FileOutputStream(path+sep+fileName);//创建文件流  
			    ws.write(fileOut);//把Workbook对象输出到路径path中  
			    fileOut.close();
				HSSFWorkbook book=doExpDealConsumptionDetail(customerConsume,path+sep+fileName);
				if(book==null) {
					request.setAttribute("error", "该时间区间没有数据需要导出");
					return "errors/error";
				}
				book.write(new FileOutputStream(path+sep+fileName));
				
				//设置下载文件名
				String url=java.net.URLDecoder.decode(path+sep+fileName,"UTF-8");
				fileName=fileName.substring(fileName.lastIndexOf("_")+1);
				fileName=URLEncoder.encode(fileName, "UTF-8");
				response.addHeader("content-disposition","attachment;filename="+fileName);
				response.setHeader("content-type","text/html;charset=utf-8");
				response.setContentType("application/x-download");
				request.setCharacterEncoding("UTF-8");
				//下载操作
				File downLoadFile=new File(url);
				OutputStream out=response.getOutputStream();
				InputStream in=new FileInputStream(downLoadFile);
				byte[] b=new byte[1024];
				@SuppressWarnings("unused")
				int ch=0;
				while((ch=in.read(b))!=-1) {
					out.write(b,0,b.length);
				}
				in.close();
				return null;
			} catch (IOException e) {
				request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
				e.printStackTrace();
				return "errors/error";
			}
		}
	}
	
	public HSSFWorkbook doExpDealFormData(CustomerConsume customerConsume,String path) {
		try {
			PageView<CustomerConsume> page = new PageView<CustomerConsume>();
			page.setPageNow(1);
			page.setPageSize(1000000);
			
			
			PageView<CustomerConsume> pageView = customerConsumeManageService.queryCustomerConsume(page, customerConsume);
			@SuppressWarnings("unchecked")
			List<CustomerConsume> list = pageView.getRecords();
			if(list==null || list.isEmpty()) {
				return null;
			}
			HSSFWorkbook book=new HSSFWorkbook(new FileInputStream(new File(path)));
			//创建excel文件对象  
	        HSSFSheet sheet = book.createSheet();
	        //创建第一行  
	        HSSFRow headRow = sheet.createRow(0);
	        //创建第一个单元格
	        HSSFCell headCell = headRow.createCell(0);
	        headCell.setCellValue("会员编号");
	        headCell= headRow.createCell(1);
	        headCell.setCellValue("业务类型");
	        headCell= headRow.createCell(2);
	        headCell.setCellValue("预计消耗日期");
	        headCell= headRow.createCell(3);
	        headCell.setCellValue("预计消耗金额");
	        headCell= headRow.createCell(4);
	        headCell.setCellValue("商品名称");
	        headCell= headRow.createCell(5);
	        headCell.setCellValue("商品个数");
	        headCell= headRow.createCell(6);
	        headCell.setCellValue("流程阶段");
	        headCell= headRow.createCell(7);
	        headCell.setCellValue("所属人");
	        headCell= headRow.createCell(8);
	        headCell.setCellValue("所属分公司");
	        headCell= headRow.createCell(9);
	        headCell.setCellValue("客户类型");
	        headCell= headRow.createCell(10);
	        headCell.setCellValue("修改时间");
	        // 文件头字体  
//	        Font font = book.createFont();
//	        font.setFontName("宋体");  
//	        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//	        font.setItalic(false);
//	        font.setFontHeight((short)200);
	        for(int i=0;i<list.size();i++) {
	        	CustomerConsume cc=list.get(i);
	        	
				// 创建第一行
				HSSFRow row = sheet.createRow(i+1);
				// 创建第一个单元格
				HSSFCell cell = row.createCell(0);
				cell.setCellValue(cc.getCusId());
				cell = row.createCell(1);
				cell.setCellValue(cc.getBusinessType());
				cell = row.createCell(2);
				cell.setCellValue(cc.getDate());
				cell = row.createCell(3);
				cell.setCellValue(cc.getAmount());
				cell = row.createCell(4);
				cell.setCellValue(cc.getProductName());
				cell = row.createCell(5);
				cell.setCellValue(cc.getGoodsCount());
				cell = row.createCell(6);
				cell.setCellValue(cc.getConsumePhase());
				cell = row.createCell(7);
				cell.setCellValue(cc.getEname());
				cell = row.createCell(8);
				cell.setCellValue(cc.getCompanyName());
				cell = row.createCell(9);
				cell.setCellValue(cc.getCustomType());
				cell = row.createCell(10);
				cell.setCellValue(cc.getUpdateTime());
	        }
	        return book;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public HSSFWorkbook doExpDealConsumptionDetail(CustomerConsume customerConsume,String path) {
		try {
			
			List<AgentConsume> agentConsumeList = orderService.getAgentConsume(customerConsume);
			if(agentConsumeList==null || agentConsumeList.isEmpty()) {
				return null;
			}
			HSSFWorkbook book=new HSSFWorkbook(new FileInputStream(new File(path)));
			//创建excel文件对象  
	        HSSFSheet sheet = book.createSheet();
	        //创建第一行  
	        HSSFRow headRow = sheet.createRow(0);
	        //创建第一个单元格
	        HSSFCell headCell = headRow.createCell(0);
	        headCell.setCellValue("商品名称");
	        headCell= headRow.createCell(1);
	        headCell.setCellValue("服务编号");
	        headCell= headRow.createCell(2);
	        headCell.setCellValue("订单号");
	        headCell= headRow.createCell(3);
	        headCell.setCellValue("商品类型");
	        headCell= headRow.createCell(4);
	        headCell.setCellValue("商品价格");
	        headCell= headRow.createCell(5);
	        headCell.setCellValue("域名");
	        headCell= headRow.createCell(6);
	        headCell.setCellValue("是否退费");
	        headCell= headRow.createCell(7);
	        headCell.setCellValue("方式");
	        headCell= headRow.createCell(8);
	        headCell.setCellValue("会员号");
	        headCell= headRow.createCell(9);
	        headCell.setCellValue("操作时间");
	        headCell= headRow.createCell(10);
	        headCell.setCellValue("销售人员");
	        headCell= headRow.createCell(11);
	        headCell.setCellValue("所属分公司");
	        headCell= headRow.createCell(12);
	        headCell.setCellValue("年限");
	        headCell= headRow.createCell(13);
	        headCell.setCellValue("年限单位");
	        headCell= headRow.createCell(14);
	        headCell.setCellValue("备注");
	        // 文件头字体  
//	        Font font = book.createFont();
//	        font.setFontName("宋体");  
//	        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//	        font.setItalic(false);
//	        font.setFontHeight((short)200);
	        for(int i=0;i<agentConsumeList.size();i++) {
	        	AgentConsume cc=agentConsumeList.get(i);
	        	
				// 创建第一行
				HSSFRow row = sheet.createRow(i+1);
				// 创建第一个单元格
				HSSFCell cell = row.createCell(0);
				cell.setCellValue(cc.getGoodsName());
				cell = row.createCell(1);
				cell.setCellValue(cc.getServiceCode());
				cell = row.createCell(2);
				cell.setCellValue(cc.getOrderCode());
				cell = row.createCell(3);
				cell.setCellValue(cc.getGoodsType());
				cell = row.createCell(4);
				cell.setCellValue(cc.getGoodsPrice());
				cell = row.createCell(5);
				cell.setCellValue(cc.getDomainName());
				cell = row.createCell(6);
				cell.setCellValue(cc.getIsReturn());
				cell = row.createCell(7);
				cell.setCellValue(cc.getOrderType());
				cell = row.createCell(8);
				cell.setCellValue(cc.getAgentCode());
				cell = row.createCell(9);
				cell.setCellValue(cc.getOperateTime());
				cell = row.createCell(10);
				cell.setCellValue(cc.getSalesManName());
				cell = row.createCell(11);
				cell.setCellValue(cc.getSubCompanyName());
				cell = row.createCell(12);
				cell.setCellValue(cc.getTimeAmount());
				cell = row.createCell(13);
				cell.setCellValue(cc.getTimeUnit());
				cell = row.createCell(14);
				cell.setCellValue(cc.getRemark());
	        }
	        return book;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 
	 * 方法描述：添加沟通记录 ,若为意向客户，则进行客户状态流转
	 * 
	 * @param customerConsume
	 * 
	 * @author 邢泽江
	 * 
	 *         2016年10月26日17:28:56
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/addCommunicationRecord")
	public String addCommunicationRecord(CustomerConsume customerConsume,
			HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Emp emp = (Emp) session.getAttribute("currentUser");
		/*if (null == emp) {
			return ;
		}*/
		PrintWriter pw = response.getWriter();
		try {
			customerConsume.setId(UUID.randomUUID().toString());
			customerConsume.setEmpId(emp.getEmpno());
			customerConsumeManageService.addCustomerConsume(customerConsume);
		} catch(RuntimeException re){
			pw.println("添加失败,交易已存在！");
		} catch (Exception e) {
			pw.println("添加失败！");
		}

			
		//判定接收客户的意向 ，即意向产品不为空
		String product = customerConsume.getProduct();
		if(product!=null||product!=""){
			intentionCustomTransferService.handlerToIntentionCustomer(customerConsume);
		}
		
		String contextPath = request.getContextPath();
		
		return "redirect:/page/goCustomerDetails?customId="+customerConsume.getCusId();
	}
	

}
